package jnpf.service.impl;

import jnpf.base.ActionResult;
import jnpf.base.service.BillRuleService;
import jnpf.model.themeLog.EntityQuery;
import jnpf.model.page.MyPageListVO;
import jnpf.entity.*;
import jnpf.mapper.TemplateMapper;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.template.*;

import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;

import jnpf.model.QueryModel;

import java.util.stream.Collectors;

import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import jnpf.util.*;

import java.util.*;

import jnpf.util.UserProvider;
import jnpf.base.UserInfo;

/**
 * template
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-10
 */
@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, TemplateEntity> implements TemplateService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private TemplateCategoryService templateCategoryService;
    @Autowired
    private TemplateAttributeService templateAttributeService;
    @Autowired
    private EntityService entityService;
    @Autowired
    private UserService userService;


    @Override
    public List<TemplateEntity> getList(TemplatePagination templatePagination) {
        return getTypeList(templatePagination, templatePagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<TemplateEntity> getTypeList(TemplatePagination templatePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? TemplateConstant.getAppColumnData() : TemplateConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total = 0;
        int templateNum = 0;
        QueryWrapper<TemplateEntity> templateQueryWrapper = new QueryWrapper<>();
        int templateAttributeNum = 0;
        QueryWrapper<TemplateAttributeEntity> templateAttributeQueryWrapper = new QueryWrapper<>();
        int templateCategoryNum = 0;
        QueryWrapper<TemplateCategoryEntity> templateCategoryQueryWrapper = new QueryWrapper<>();
        long templateAttributecount = templateAttributeService.count();
        long templateCategorycount = templateCategoryService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(templatePagination.getSuperQueryJson())) {
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            String queryJson = templatePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<TemplateEntity> templateSuperWrapper = new QueryWrapper<>();
            templateSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(templateSuperWrapper, TemplateEntity.class, queryJson, "0"));
            int templateNum1 = templateSuperWrapper.getExpression().getNormal().size();
            if (templateNum1 > 0) {
                List<String> templateList = this.list(templateSuperWrapper).stream().map(TemplateEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(templateList);
                intersectionSuperList.add(templateList);
                superNum++;
            }
            String templateAttributeTable = "template_attribute";
            boolean templateAttributeHasSql = queryJson.contains(templateAttributeTable);
            List<String> templateAttributeList = generaterSwapUtil.selectIdsByChildCondition(TemplateConstant.getTableList(), templateAttributeTable, queryJson, null);
            if (templateAttributeHasSql) {
                allSuperList.addAll(templateAttributeList);
                intersectionSuperList.add(templateAttributeList);
                superNum++;
            }
            String templateCategoryTable = "template_category";
            boolean templateCategoryHasSql = queryJson.contains(templateCategoryTable);
            List<String> templateCategoryList = generaterSwapUtil.selectIdsByChildCondition(TemplateConstant.getTableList(), templateCategoryTable, queryJson, null);
            if (templateCategoryHasSql) {
                allSuperList.addAll(templateCategoryList);
                intersectionSuperList.add(templateCategoryList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if (superOp.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp = "";
        if (ObjectUtil.isNotEmpty(ruleJson)) {
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<TemplateEntity> templateSuperWrapper = new QueryWrapper<>();
            templateSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(templateSuperWrapper, TemplateEntity.class, ruleJson, "0"));
            int templateNum1 = templateSuperWrapper.getExpression().getNormal().size();
            if (templateNum1 > 0) {
                List<String> templateList = this.list(templateSuperWrapper).stream().map(TemplateEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(templateList);
                intersectionRuleList.add(templateList);
                ruleNum++;
            }
            String templateAttributeTable = "template_attribute";
            boolean templateAttributeHasSql = ruleJson.contains(templateAttributeTable);
            List<String> templateAttributeList = generaterSwapUtil.selectIdsByChildCondition(TemplateConstant.getTableList(), templateAttributeTable, ruleJson, null);
            if (templateAttributeHasSql) {
                allRuleList.addAll(templateAttributeList);
                intersectionRuleList.add(templateAttributeList);
                ruleNum++;
            }
            String templateCategoryTable = "template_category";
            boolean templateCategoryHasSql = ruleJson.contains(templateCategoryTable);
            List<String> templateCategoryList = generaterSwapUtil.selectIdsByChildCondition(TemplateConstant.getTableList(), templateCategoryTable, ruleJson, null);
            if (templateCategoryHasSql) {
                allRuleList.addAll(templateCategoryList);
                intersectionRuleList.add(templateCategoryList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if (ruleOp.equalsIgnoreCase("and")) {
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            } else {
                allRuleIDlist = allRuleList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object templateObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(templateQueryWrapper, TemplateEntity.class, templatePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(templateObj)) {
                    return new ArrayList<>();
                } else {
                    templateQueryWrapper = (QueryWrapper<TemplateEntity>) templateObj;
                    if (templateQueryWrapper.getExpression().getNormal().size() > 0) {
                        templateNum++;
                    }
                }
                Object templateAttributeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(templateAttributeQueryWrapper, TemplateAttributeEntity.class, templatePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(templateAttributeObj)) {
                    return new ArrayList<>();
                } else {
                    templateAttributeQueryWrapper = (QueryWrapper<TemplateAttributeEntity>) templateAttributeObj;
                    if (templateAttributeQueryWrapper.getExpression().getNormal().size() > 0) {
                        templateAttributeNum++;
                    }
                }
                Object templateCategoryObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(templateCategoryQueryWrapper, TemplateCategoryEntity.class, templatePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(templateCategoryObj)) {
                    return new ArrayList<>();
                } else {
                    templateCategoryQueryWrapper = (QueryWrapper<TemplateCategoryEntity>) templateCategoryObj;
                    if (templateCategoryQueryWrapper.getExpression().getNormal().size() > 0) {
                        templateCategoryNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object templateObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(templateQueryWrapper, TemplateEntity.class, templatePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(templateObj)) {
                    return new ArrayList<>();
                } else {
                    templateQueryWrapper = (QueryWrapper<TemplateEntity>) templateObj;
                    if (templateQueryWrapper.getExpression().getNormal().size() > 0) {
                        templateNum++;
                    }
                }


                Object templateAttributeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(templateAttributeQueryWrapper, TemplateAttributeEntity.class, templatePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(templateAttributeObj)) {
                    return new ArrayList<>();
                } else {
                    templateAttributeQueryWrapper = (QueryWrapper<TemplateAttributeEntity>) templateAttributeObj;
                    if (templateAttributeQueryWrapper.getExpression().getNormal().size() > 0) {
                        templateAttributeNum++;
                    }
                }


                Object templateCategoryObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(templateCategoryQueryWrapper, TemplateCategoryEntity.class, templatePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(templateCategoryObj)) {
                    return new ArrayList<>();
                } else {
                    templateCategoryQueryWrapper = (QueryWrapper<TemplateCategoryEntity>) templateCategoryObj;
                    if (templateCategoryQueryWrapper.getExpression().getNormal().size() > 0) {
                        templateCategoryNum++;
                    }
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(templatePagination.getName())) {
                templateNum++;

                String value = templatePagination.getName() instanceof List ? JsonUtil.getObjectToString(templatePagination.getName()) : String.valueOf(templatePagination.getName());
                templateQueryWrapper.lambda().like(TemplateEntity::getName, value);

            }

        }
        if (templateAttributeNum > 0) {
            List<String> templateAttributeIdList = templateAttributeService.list(templateAttributeQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getTemplateId())).map(t -> t.getTemplateId()).collect(Collectors.toList());
            long count = templateAttributeService.count();
            if (count > 0) {
                intersectionList.add(templateAttributeIdList);
            }
            AllIdList.addAll(templateAttributeIdList);
        }
        total += templateAttributeNum;
        if (templateCategoryNum > 0) {
            List<String> templateCategoryIdList = templateCategoryService.list(templateCategoryQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getTemplateId())).map(t -> t.getTemplateId()).collect(Collectors.toList());
            long count = templateCategoryService.count();
            if (count > 0) {
                intersectionList.add(templateCategoryIdList);
            }
            AllIdList.addAll(templateCategoryIdList);
        }
        total += templateCategoryNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            templateQueryWrapper.lambda().in(TemplateEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            templateQueryWrapper.lambda().and(t -> t.in(TemplateEntity::getId, finalAllSuperIDlist));
        }
        //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)) {
            if (allRuleIDlist.size() == 0) {
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            templateQueryWrapper.lambda().and(t -> t.in(TemplateEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if (StringUtil.isEmpty(templatePagination.getSidx())) {
            templateQueryWrapper.lambda().orderByDesc(TemplateEntity::getId);
        } else {
            try {
                String sidx = templatePagination.getSidx();
                String[] strs = sidx.split("_name");
                TemplateEntity templateEntity = new TemplateEntity();
                Field declaredField = templateEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                templateQueryWrapper = "asc".equals(templatePagination.getSort().toLowerCase()) ? templateQueryWrapper.orderByAsc(value) : templateQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<TemplateEntity> page = new Page<>(templatePagination.getCurrentPage(), templatePagination.getPageSize());
                IPage<TemplateEntity> userIPage = this.page(page, templateQueryWrapper);
                return templatePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<TemplateEntity> list = new ArrayList();
                return templatePagination.setData(list, list.size());
            }
        } else {
            return this.list(templateQueryWrapper);
        }
    }

    @Override
    public TemplateEntity getInfo(String id) {
        QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TemplateEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(TemplateEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, TemplateEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(TemplateEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * TemplateCategory子表方法
     */
    @Override
    public List<TemplateCategoryEntity> getTemplateCategoryList(String id, TemplatePagination templatePagination) {
        Map<String, Object> newtabMap = TemplateConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "templateCategory";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<TemplateCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = templateCategoryService.getChild(templatePagination, queryWrapper);
        queryWrapper.lambda().eq(TemplateCategoryEntity::getTemplateId, id);
        generaterSwapUtil.wrapperHandle(TemplateConstant.getColumnData(), TemplateConstant.getAppColumnData(), queryWrapper, TemplateCategoryEntity.class, "sub", tableName);
        return templateCategoryService.list(queryWrapper);
    }

    /**
     * TemplateCategory子表方法
     */
    @Override
    public List<TemplateCategoryEntity> getTemplateCategoryList(String id) {
        QueryWrapper<TemplateCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TemplateCategoryEntity::getTemplateId, id);
        return templateCategoryService.list(queryWrapper);
    }

    /**
     * TemplateAttribute子表方法
     */
    @Override
    public List<TemplateAttributeEntity> getTemplateAttributeList(String id, TemplatePagination templatePagination) {
        Map<String, Object> newtabMap = TemplateConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "templateAttribute";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<TemplateAttributeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = templateAttributeService.getChild(templatePagination, queryWrapper);
        queryWrapper.lambda().eq(TemplateAttributeEntity::getTemplateId, id);
        generaterSwapUtil.wrapperHandle(TemplateConstant.getColumnData(), TemplateConstant.getAppColumnData(), queryWrapper, TemplateAttributeEntity.class, "sub", tableName);
        return templateAttributeService.list(queryWrapper);
    }

    /**
     * TemplateAttribute子表方法
     */
    @Override
    public List<TemplateAttributeEntity> getTemplateAttributeList(String id) {
        QueryWrapper<TemplateAttributeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TemplateAttributeEntity::getTemplateId, id);
        return templateAttributeService.list(queryWrapper);
    }

    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(TemplateForm form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        //主表字段验证
        if (StringUtil.isEmpty(form.getName())) {
            return "模板名称不能为空";
        }
        //子表字段验证
        if (form.getTemplateCategoryList() != null) {
            for (TemplateCategoryModel t : form.getTemplateCategoryList()) {
                if (StringUtil.isNotEmpty(t.getCategory())) {
                    t.setCategory(t.getCategory().trim());
                } else {
                    return "模板分类表-分类名称不能为空";
                }
            }
        }
//            if (form.getTemplateAttributeList()!=null){
//                        for(TemplateAttributeModel t : form.getTemplateAttributeList()){
//                            if(StringUtil.isNotEmpty(t.getAttrName())){
//                                t.setAttrName(t.getAttrName().trim());
//                            }
//                            else{
//                                return "属性值-属性名称不能为空";
//                            }
//                        }
//            }
        return countRecover;
    }


    @Override
    @Transactional
    public void saveOrUpdate(TemplateEntity entity, String id, boolean isSave) throws Exception {
        UserInfo userInfo = userProvider.get();

        // 情况1：没有id，为保存新增记录
        if (isSave) {
            entity.setId(RandomUtil.uuId());
            entity.setVersion(1);
            entity.setIsMain("1");
            entity.setType("3");
            entity.setIsDefault(2);
            entity.setFirstUpdateId(entity.getId());
        }
        // 情况2：有id且isUpdate为true，需要新创建一个模板
        else if (entity.getIsUpdate() != null && entity.getIsUpdate()) {
            TemplateEntity oldEntity = this.getById(entity.getId());
            if (oldEntity != null) {
                entity.setFirstUpdateId(oldEntity.getFirstUpdateId());
                entity.setVersion(oldEntity.getVersion() + 1);
                entity.setLastUpdateId(oldEntity.getId());
                // 直接使用原始名称，不添加版本后缀
                entity.setName(oldEntity.getName());
                entity.setId(RandomUtil.uuId());
                entity.setIsMain("2");
            }
        }

        entity.setCreateUserId(userInfo.getUserId());
        entity.setCreateTime(DateUtil.getNowDate());
        this.saveOrUpdate(entity);

        // 处理TemplateCategory子表数据(1对多)
        if (!isSave) {
            QueryWrapper<TemplateCategoryEntity> categoryQueryWrapper = new QueryWrapper<>();
            categoryQueryWrapper.lambda().eq(TemplateCategoryEntity::getTemplateId, entity.getId());
            templateCategoryService.remove(categoryQueryWrapper);
        }
        if (entity.getTemplateCategoryEntityArrayList() != null && !entity.getTemplateCategoryEntityArrayList().isEmpty()) {
            // 保存分类数据
            List<TemplateCategoryEntity> categories = entity.getTemplateCategoryEntityArrayList().stream().peek(category -> {
                category.setId(RandomUtil.uuId());
                category.setTemplateId(entity.getId());
                category.setCreateUserId(userInfo.getUserId());
                category.setCreateTime(DateUtil.getNowDate());
            }).collect(Collectors.toList());
            templateCategoryService.saveBatch(categories);


            // 属性值
            // 先删除旧属性
            if (!isSave) {
                QueryWrapper<TemplateAttributeEntity> attributeQueryWrapper = new QueryWrapper<>();
                attributeQueryWrapper.lambda().eq(TemplateAttributeEntity::getTemplateId, entity.getId());
                templateAttributeService.remove(attributeQueryWrapper);
            }

            //处理每个分类下的属性数据(多对多)
            for (TemplateCategoryEntity category : categories) {
                if (category.getTemplateCategoryEntityArrayList() != null && !category.getTemplateCategoryEntityArrayList().isEmpty()) {

                    // 保存新属性
                    List<TemplateAttributeEntity> attributes = category.getTemplateCategoryEntityArrayList().stream().peek(attribute -> {
                        attribute.setId(RandomUtil.uuId());
                        attribute.setTemplateId(entity.getId());
                        attribute.setCategoryId(category.getId());
                        attribute.setCreateUserId(userInfo.getUserId());
                        List<String> selectValueList = attribute.getAttrSelectValueDTO();
                        if (selectValueList != null) {
                            String selectValueJsonStr = JsonUtil.getListToJsonArray(selectValueList).toJSONString();
                            attribute.setAttrSelectValue(selectValueJsonStr);
                        }
                        attribute.setCreateTime(DateUtil.getNowDate());
                    }).collect(Collectors.toList());
                    templateAttributeService.saveBatch(attributes);
                }
            }
        }
    }

    @Override
    public ActionResult getEntityCount(String templateId) {
        QueryWrapper<EntityEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EntityEntity::getTemplateId, templateId);
        long count = entityService.count(queryWrapper);
        return ActionResult.success(count);
    }

    @Override
    public MyPageListVO<EntityEntity> getTemplateEntityList(String templateId, EntityQuery pagination) {
        QueryWrapper<EntityEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EntityEntity::getTemplateId, templateId);

        // 添加查询条件
        if (StringUtil.isNotEmpty(pagination.getEntityName())) {
            queryWrapper.lambda().like(EntityEntity::getName, pagination.getEntityName());
        }

        // 分页查询
        Page<EntityEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<EntityEntity> entityPage = entityService.page(page, queryWrapper);

        // 批量获取用户信息并设置
        List<EntityEntity> records = entityPage.getRecords();
        List<String> userIds = records.stream()
                .map(EntityEntity::getBelongUserId)
                .filter(StringUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());

        if (!userIds.isEmpty()) {
            Map<String, String> userMap = userService.listByIds(userIds).stream()
                    .collect(Collectors.toMap(
                            UserEntity::getId,
                            UserEntity::getRealName,
                            (oldValue, newValue) -> oldValue
                    ));

            records.forEach(entity -> {
                String realName = userMap.get(entity.getBelongUserId());
                if (realName != null) {
                    entity.setBelongUserId(realName);
                }
            });
        }

        // 构建返回结果
        MyPageListVO<EntityEntity> result = new MyPageListVO<>();
        result.setList(records);
        result.setPagination(pagination);
        result.getPagination().setTotal(entityPage.getTotal());
        return result;
    }

    @Override
    public String checkForm(TemplateEntity entity, int i) {
        if (StringUtil.isEmpty(entity.getName())) {
            return "模板名称不能为空";
        }
        if (entity.getTemplateCategoryEntityArrayList() != null) {
            for (TemplateCategoryEntity category : entity.getTemplateCategoryEntityArrayList()) {
                if (StringUtil.isEmpty(category.getCategory())) {
                    return "模板分类表-分类名称不能为空";
                }
                // 检查分类下的属性
                if (category.getTemplateCategoryEntityArrayList() != null) {
                    for (TemplateAttributeEntity attribute : category.getTemplateCategoryEntityArrayList()) {
                        if (StringUtil.isEmpty(attribute.getAttrName())) {
                            return "属性名称不能为空";
                        }
                    }
                }
            }
        }
        return "";
    }
}
